import { Injectable } from '@nestjs/common';
import { CreateRechargeDto } from './dto/create-recharge.dto';
import { UpdateRechargeDto } from './dto/update-recharge.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Recharge } from './entities/recharge.entity';
import { UserService } from '../user/user.service';
import { formatError, formatPage, formatSuccess, jingDuSum } from 'src/util';

@Injectable()
export class RechargeService {
  constructor(
    @InjectRepository(Recharge)
    private readonly rechargeRepository: Repository<Recharge>,
    private readonly userService: UserService,
  ) {}

  // 列表
  async findAll(params) {
    const pageNum = params.pageNum || 1;
    const pageSize = params.pageSize || 10;
    // 查询条件
    const where: any = {
      userId: Number(params?.userId),
    };
    // 获取总条数
    const total = await this.rechargeRepository.count({ where });
    // 查第几页的数据
    let list = [];
    if (total > 0) {
      list = await this.rechargeRepository.find({
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
        where,
        order: { create_time: 'DESC' },
      });
    }
    return formatPage({ pageNum, pageSize, total, list });
  }

  // 新增
  async create(createRechargeDto: CreateRechargeDto) {
    const userId = createRechargeDto.userId;
    // 获取用户当前余额
    const user = await this.userService.findOneById(Number(userId));
    if (!user) {
      return formatError({ msg: '用户不存在' });
    }
    const afterMoney = jingDuSum([user?.balance, createRechargeDto.money]);
    const params = {
      userId,
      last: user?.balance,
      money: createRechargeDto.money,
      afterMoney,
    };
    const data = await this.rechargeRepository.save(params);
    // 更新用户余额
    const userMondy = await this.userService.edit({ id: Number(userId), balance: afterMoney });
    return formatSuccess('成功');
  }
}
